package com.djhu.hbase;
/**
 * Created by zw on 2017/12/21.
 */

import org.apache.commons.lang.StringUtils;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.hadoop.hbase.HbaseTemplate;

import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.List;

/**
 * code is far away from bug with the animal protecting
 * ┏┓　　　┏┓
 * ┏┛┻━━━┛┻┓
 * ┃　　　　　　　┃
 * ┃　　　━　　　┃
 * ┃　┳┛　┗┳　┃
 * ┃　　　　　　　┃
 * ┃　　　┻　　　┃
 * ┃　　　　　　　┃
 * ┗━┓　　　┏━┛
 * 　　┃　　　┃神兽保佑
 * 　　┃　　　┃代码无BUG！
 * 　　┃　　　┗━━━┓
 * 　　┃　　　　　　　┣┓
 * 　　┃　　　　　　　┏┛
 * 　　┗┓┓┏━┳┓┏┛
 * 　　　┃┫┫　┃┫┫
 * 　　　┗┻┛　┗┻┛
 *
 * <p>
 * ---------------------------------
 */
@Configuration
@EnableConfigurationProperties(HBaseProperties.class)
@ConditionalOnClass({HbaseTemplate.class})
@ConditionalOnProperty(prefix = "spring.boot.djhu.hbase", value="enabled", matchIfMissing =false )
public class HBaseAutoConfiguration {

    @Autowired
    private HBaseProperties hBaseProperties;

    @Bean
    org.apache.hadoop.conf.Configuration hbaseConfiguration() throws FileNotFoundException {
        //org.apache.hadoop.conf.Configuration configuration = new org.apache.hadoop.conf.Configuration();

        org.apache.hadoop.conf.Configuration configuration = HBaseConfiguration.create();
        if (!StringUtils.isEmpty(hBaseProperties.getResource())){
            List<String> paths = Arrays.asList(hBaseProperties.getResource().split(","));
            for (String path:paths){
                configuration.addResource(new Path(path));
            }
        }else {

            configuration.set("hbase.zookeeper.quorum", hBaseProperties.getUrl());
            configuration.set("hbase.zookeeper.property.clientPort", String.valueOf(hBaseProperties.getPort()));
        }
        return configuration;
    }

    @Bean
    HbaseTemplate hbaseTemplate(org.apache.hadoop.conf.Configuration hbaseConfiguration){
        HbaseTemplate hbaseTemplate = new HbaseTemplate(hbaseConfiguration);
        return hbaseTemplate;
    }

    @Bean HBaseOperator hBaseOperator(HbaseTemplate hbaseTemplate,org.apache.hadoop.conf.Configuration configuration){
        HBaseOperator hBaseOperator = new HBaseOperator();
        hBaseOperator.setHbaseTemplate(hbaseTemplate);
        hBaseOperator.setConfiguration(configuration);
        return hBaseOperator;
    }

}